import { reactive, provide } from 'vue'

export const useChildren = (key: any) => {
  const publicChildren: any = reactive([])
  const internalChildren: any = reactive([])
  // const parent = getCurrentInstance()
  // console.log(parent)

  const linkChildren = (value: any) => {
    const link = (child: any) => {
      if (child.proxy) {
        internalChildren.push(child)
        publicChildren.push(child.proxy)
      }
    }

    const unlink = (child: any) => {
      const index = internalChildren.indexOf(child)
      publicChildren.splice(index, 1)
      internalChildren.splice(index, 1)
    }

    provide(
      key,
      Object.assign(
        {
          link,
          unlink,
          children: publicChildren,
          internalChildren,
        },
        value,
      ),
    )
  }
  return {
    children: publicChildren,
    internalChildren,
    linkChildren,
  }
}
